package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

type UserQueryParam struct {
	BaseQueryParam
	Mobile   string
	RealName string
}

type User struct {
	Id         int
	Nickname   string
	Mobile     string
	Password   string
	RealName   string
	Openid     string
	LoginTime  int
	LoginTimes int
	LoginIp    string
	Sex        int
	Lat        string
	Lng        string
	Avatar     string
	CreateAt   time.Time `orm:"auto_now_add;type(datetime)"`
	Status     int
}

func init() {
	orm.RegisterModel(new(User))
}

func (*User) TableName() string {
	return UserTBName()
}

func UserTBName() string {
	return TableName("user")
}

func UserOne(id int) (*User, error) {
	o := orm.NewOrm()
	m := User{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

func UserPageList(params *UserQueryParam) ([]*User, int64) {
	query := orm.NewOrm().QueryTable(UserTBName())
	data := make([]*User, 0)
	sort := "Id"
	switch params.Sort {
	case "Id":
		sort = "Id"
	case "Mobile":
		sort = "Mobile"
	}

	if params.Order == "desc" {
		sort = "-" + sort
	}
	if len(params.Mobile) > 0 {
		query = query.Filter("Mobile__istartswith", params.Mobile)
	}
	if len(params.RealName) > 0 {
		query = query.Filter("realname__istartswith", params.RealName)
	}

	total, _ := query.Count()
	query.OrderBy(sort).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}
